package com.haisen.common.utils;

import java.util.Random;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.CyclicBarrier;

/**
 * <p>〈功能概述〉.
 *
 * @author haisen /20227/18
 */
public class ThreadUtil extends jodd.util.ThreadUtil {
    
    public static void printState(Thread t1) {
        System.out.println(t1.getState());
    }

    @FunctionalInterface
    interface ContextRunnable {
        public void run(int index);
    }

    public static void run(int count, Runnable task) throws InterruptedException {
        ContextRunnable innerTask = ($) -> task.run();
        run(count, innerTask);
    }

    public static void run(int count, ContextRunnable task) throws InterruptedException {
        CyclicBarrier barrier = new CyclicBarrier(count);
        CountDownLatch latch = new CountDownLatch(count);

        for (int i = 0; i < count; i++) {
            final int index = i;
            Runnable wrapperTask = () -> {
                try {
                    barrier.await();
                } catch (InterruptedException | BrokenBarrierException e) {
                    e.printStackTrace();
                }
                task.run(index);
                latch.countDown();
            };
            new Thread(wrapperTask, "demo-" + i).start();
        }
        latch.await();
    }

    public static Runnable repeatRun(int count, Runnable task) {
        return () -> {
            for (int i = 0; i < count; i++) {
                task.run();
            }
        };
    }

    public static void safeSleep(int millis) {
        try {
            Thread.sleep(millis);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }

    public static void randomSleep(int maxMillis) {
        Random random = new Random();
        safeSleep(random.nextInt(maxMillis));
    }
}
